package org.example;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import org.example.router.RequestRouter;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

/**
 * HTTP服务器 - 重构为可配置的独立组件
 */
public class BettingServer {
    private HttpServer server;
    private RequestRouter router;
    private int port = 8001;
    private int threadPoolSize = 50;

    public BettingServer() {
        this.router = new RequestRouter();
    }

    public void start() throws IOException {
        server = HttpServer.create(new InetSocketAddress(port), 0);

        server.createContext("/", exchange -> {
            try {
                String method = exchange.getRequestMethod();
                String path = exchange.getRequestURI().getPath();

                // 查找并处理路由
                RequestRouter.RouteMatch routeMatch = router.findAndHandleRoute(method, path, exchange);

                if (routeMatch != null) {
                    handleResult(exchange, routeMatch.result);
                } else {
                    sendResponse(exchange, "404 Not Found", 404);
                }

            } catch (Exception e) {
                sendResponse(exchange, "500 Internal Server Error", 500);
                e.printStackTrace();
            } finally {
                exchange.close();
            }
        });

        server.setExecutor(Executors.newFixedThreadPool(threadPoolSize));
        server.start();

        System.out.println("Server started on port " + port);
        System.out.println("Registered routes: " + router.getRegisteredRoutes());
    }

    private void handleResult(HttpExchange exchange, String result) throws IOException {
        if (result.startsWith("SUCCESS:")) {
            String[] parts = result.split(":", 3);
            int statusCode = Integer.parseInt(parts[1]);
            String responseBody = parts[2];

            if (responseBody.isEmpty()) {
                exchange.sendResponseHeaders(statusCode, -1);
            } else {
                sendResponse(exchange, responseBody, statusCode);
            }
        } else if (result.startsWith("ERROR:")) {
            String[] parts = result.split(":", 3);
            int statusCode = Integer.parseInt(parts[1]);
            String errorMessage = parts[2];
            sendResponse(exchange, errorMessage, statusCode);
        } else {
            sendResponse(exchange, result, 200);
        }
    }

    private void sendResponse(HttpExchange exchange, String response, int statusCode) throws IOException {
        byte[] responseBytes = response.getBytes();
        exchange.sendResponseHeaders(statusCode, responseBytes.length);
        try (OutputStream os = exchange.getResponseBody()) {
            os.write(responseBytes);
        }
    }

    public void stop() {
        if (server != null) {
            server.stop(0);
            System.out.println("Server stopped");
        }
    }

    /**
     * 获取监控信息
     */
    public void printMonitoringInfo() {
        System.out.println("=== Server Monitoring ===");
        System.out.println("Server Status: " + (server != null ? "RUNNING" : "STOPPED"));
        System.out.println("Port: " + port);
        System.out.println("Registered Routes: " + router.getRegisteredRoutes().size());
    }

    // Getter and Setter methods
    public RequestRouter getRouter() {
        return router;
    }

    public void setRouter(RequestRouter router) {
        this.router = router;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getThreadPoolSize() {
        return threadPoolSize;
    }

    public void setThreadPoolSize(int threadPoolSize) {
        this.threadPoolSize = threadPoolSize;
    }


}